$.fn.extend
({
    WidgetGrid: function(options)
    {
        options.Dom = this;
        var grid = cloneObject(LrqWidgetGrid,true);
        grid.Grid(options);
        return grid;
    }
});

var LrqWidgetGrid = {
	Grid:function(options){
		var boss = this;
		boss.InitMe(options);
		boss.LoadData();
	},
	InitMe:function(options){
		var boss = this;
		boss.gridDatas = null;
		boss.PageCount = 0;
		boss.PageIndex = (options.PageIndex==null)?1:options.PageIndex;
		boss.PageSize = (options.PageSize==null)?15:options.PageSize;
		boss.RecordCount = 0;
		boss.Data = options.Data;
		boss.Url = options.url;
		boss.OnSuccess = options.OnSuccess;
		boss.OnComplete = options.OnComplete;
		boss.OnError = options.OnError;
		boss.Cloumns = options.columns;
		boss.OnRender = options.OnRender;
		boss.RowRender = options.RowRender;
		boss.HeadRender = options.HeadRender;
		boss.FootRender = options.FootRender;
		boss.Dom = options.Dom;
		boss.Checkbox = (options.Checkbox == null)?true:options.Checkbox;
		boss.evenRowClass = (options.evenRowClass==null)?"widgets_grid_table_td_even":options.evenRowClass;
		boss.oddRowClass = (options.oddRowClass==null)?"widgets_grid_table_td_odd":options.oddRowClass;
		boss.thClass = (options.thClass==null)?"widgets_grid_table_th":options.thClass;
		boss.trClass = (options.trClass==null)?"widgets_grid_table_tr":options.trClass;
		boss.ftClass = (options.ftClass==null)?"widget_grid_table_td_foot":options.ftClass;
		boss.tableClass = (options.tableClass==null)?"widgets_grid_table":options.tableClass;
	},
	LoadData:function(){
		var boss = this;
		var Griddatas=null;
		
		sbl.ajax({
			url:boss.Url+"?grid_pageSize="+boss.PageSize+"&grid_pageIndex="+boss.PageIndex,
			data:boss.Data,
			async:false,
			success:function(d){
				Griddatas = d;
				if(boss.success)
				{
					boss.success(d);
				}
				boss.renderGrid(Griddatas);
			},
			error:function(d){
				if(boss.error)
				{
					boss.error(d);
				}
			}
		});
	},
	renderGrid:function(Griddatas){
		var boss = this;
		if(!Griddatas.pageCount){
			Griddatas = Griddatas.data;
		}
		boss.gridDatas = Griddatas;
		boss.PageCount = parseInt(Griddatas.pageCount);
		boss.PageIndex = parseInt(Griddatas.pageIndex);
		boss.PageSize = parseInt(Griddatas.pageSize);
		boss.RecordCount = parseInt(Griddatas.total);
		
		var gridContent = $('<div class="widgets_grid_scroll"></div>');
		var gridTable = $('<table class="'+boss.tableClass+'" >');
		var gridHead = $('<thead></thead>');
		var gridBody = $('<tbody></tbody>');
		var gridFoot = $('<tfoot></tfoot>');
		
		gridContent.append(gridTable.append(gridHead).append(gridBody).append(gridFoot));
		
		var gridHeadTr ;
		if(boss.HeadRender){
			gridHeadTr = boss.HeadRender(boss.Cloumns,boss.Checkbox);
		}
		else{
			gridHeadTr = $('<tr class="'+boss.trClass+'"></tr>');
			if(boss.Checkbox){
				gridHeadTr.append($('<th style="width: 45px;" class="'+boss.thClass+'"><input gridCheckAll="gridCheckAll" type="checkbox"/></th>'));
			}
			
			for(var i =0;i<boss.Cloumns.length;i++)
			{
				var cloumn = boss.Cloumns[i];
				if(cloumn)
				{
					var text = cloumn.text;
					var gridHeadTh = $('<th class="'+boss.thClass+'"></th>').html(text);
					gridHeadTr.append(gridHeadTh);
				}				
			}
		}
		
		if(gridHeadTr){
			gridHead.append(gridHeadTr);
		}
		
		if(boss.RecordCount == 0)
		{
			var colspan = boss.Cloumns.length;
			if(boss.Checkbox){
				colspan++;
			}
			var gridTr = $('<tr class="'+boss.trClass+'"><td colspan="'+colspan+'" class="'+boss.evenRowClass+'">无数据</td></tr>');
			gridBody.append(gridTr);
		}
		
		var totalRow = null;
		var totalRowAdd = false;
		
		for(var i = 0;i<Griddatas.data.length;i++)
		{
			var data = Griddatas.data[i];
			var cloneData = sbl.clone(data);
			var gridTr;
			if(boss.RowRender){
				gridTr = boss.RowRender(data,i);
			}
			else{
				if(boss.OnRender)
				{
					data = boss.OnRender(data);
				}
				gridTr = $('<tr class="'+boss.trClass+'"></tr>');
				var className = "";
				if(totalRowAdd){
					className = "totalTd";
				}
				else{
					if((i%2) == 0)
					{
						className = boss.evenRowClass;
					}
					else
					{
						className = boss.oddRowClass;
					}
				}
				
				if(boss.Checkbox){
					if(totalRowAdd){
						gridTr.append($('<td class="'+className+'">合计</td>'));
					}
					else{
						var checked = (data.rowChecked)?"checked":"";
						gridTr.append($('<td class="'+className+'" ><input '+checked+' rowIndex="'+i+'" gridCheckRow="gridCheckRow" type="checkbox"/></td>'));
					}
				}
				for(var j =0;j<boss.Cloumns.length;j++)
				{
					var cloumn = boss.Cloumns[j];
					
					if(cloumn)
					{
						var field = cloumn.field;	
						var total = cloumn.total;
						var gridTd = $('<td></td>').html(data[field]).addClass(className);
						gridTr.append(gridTd);
						
						if(total && !totalRowAdd){
							if(!totalRow){
								totalRow = {};
							}
							try {
								var numValue = parseFloat(cloneData[field]);
								var currentNumValue = totalRow[field];
								if(currentNumValue){
									currentNumValue =  parseFloat(currentNumValue);
								}
								else{
									currentNumValue = 0;
								}
								totalRow[field] = currentNumValue+numValue;
							} catch (e) {
								
							}
						}
					}
				}
			}
			if(gridTr){
				gridBody.append(gridTr);
			}
			
			if(!totalRowAdd && i == Griddatas.data.length - 1 && totalRow != null){
				Griddatas.data.push(totalRow);
				totalRowAdd = true;
			}
		}
		
		var gridFootTr;
		if(boss.FootRender){
			gridFootTr = boss.FootRender(boss.PageIndex,boss.PageCount,boss.RecordCount,boss.PageSize,boss.Cloumns,boss.Checkbox);
		}
		else{
			var colspan = boss.Cloumns.length;
			if(boss.Checkbox){
				colspan++;
			}
			var gridFootContent = '<tr class="'+boss.trClass+'">';
			gridFootContent+='<th class="'+boss.ftClass+'" colspan="'+colspan+'">';
			gridFootContent+='<div class="WidgetGridFootPage">';
			gridFootContent+='<a class="WidgetGridFootPageDisabled" href="First">首页</a>';
			gridFootContent+='<a class="WidgetGridFootPageDisabled" href="Prev">上页</a>';
			gridFootContent+='<a href="Next">下页</a>';
			gridFootContent+='<a href="Last">尾页</a>&nbsp;';
			gridFootContent+='<span >第'+boss.PageIndex+'页/共'+boss.PageCount+'页</span>&nbsp;|&nbsp;';
			gridFootContent+='<span>记录总数:'+boss.RecordCount+'</span>&nbsp;|&nbsp;';
			gridFootContent+='<span>每页显示:</span>';
			gridFootContent+='<a class="WidgetGridFootPageDisabled" >'+boss.PageSize+'</a>';
			gridFootContent+='</div>';
			gridFootContent+='</th>	';
			gridFootContent+='</tr>';
			gridFootTr = $(gridFootContent);
		}
		
		if(gridFootTr){
			gridFoot.append(gridFootTr);
		}
		
		$(boss.Dom).empty();
		$(boss.Dom).append(gridContent);
		
		$("th input[gridCheckAll='gridCheckAll']",boss.Dom).bind("click",function(){
			var checkboxs = $("td input[gridCheckRow='gridCheckRow']",boss.Dom);
			var checked = $(this).is(":checked");
			for(var cbIndex =0;cbIndex<checkboxs.length;cbIndex++){
				var checkbox = checkboxs[cbIndex];
				if(checked){
					$(checkbox).attr("checked","checked");
				}
				else{
					$(checkbox).removeAttr("checked");
				}
			}
		});
		
		$("."+boss.ftClass+" a",boss.Dom).bind("click",function(){
			var href = $(this).attr("href");
            if (href.indexOf("/") >= 0)
            {
                var all = href.split("/");
                href = all[all.length - 1];
            }
            switch (href)
            {
                case "First":
                    if (boss.PageIndex > 1)
                    {
                        boss.PageIndex = 1;
                        boss.LoadData();
                    }
                    break;
                case "Prev":
                    if (boss.PageIndex> 1)
                    {
                        boss.PageIndex--;
                        boss.LoadData();
                    }
                    break;
                case "Next":
                    if (boss.PageIndex < boss.PageCount)
                    {
                        boss.PageIndex++;
                        boss.LoadData();
                    }
                    break;
                case "Last":
                    if (boss.PageIndex < boss.PageCount)
                    {
                        boss.PageIndex = boss.PageCount;
                        boss.LoadData();
                    }
                    break;
            }
            return false;
		});
		
		$("tr."+boss.trClass,boss.Dom).bind("mouseover",function(){
			$("td",$(this)).addClass("mouseover");
		});
		$("tr."+boss.trClass,boss.Dom).bind("mouseout",function(){
			$("td",$(this)).removeClass("mouseover");
		});
		$("td",boss.Dom).bind("click",function(){
			var tds = $(this).parent().children();
			if(tds.hasClass("selected")){
				tds.removeClass("selected");
			}
			else{
				tds.addClass("selected");
			}
			
		});
		$("td input[gridCheckRow='gridCheckRow']",boss.Dom).bind("click",function(){
				var tds = $(this).parent().parent().children();
				if($(this).is(":checked")){
					tds.addClass("selected");
				}
				else{
					tds.removeClass("selected");
				}
		});
		
		if(boss.OnComplete)
		{
			boss.OnComplete(boss.Dom);
		}
	},
	getSelectRows:function(){
		var boss = this;
		var checkboxs = $("td input[gridCheckRow='gridCheckRow']:checked",boss.Dom);
		var rows = [];
		for(chIndex = 0;chIndex<checkboxs.length;chIndex++){
			var rowIndex = $(checkboxs[chIndex]).attr("rowIndex");
			var row = boss.gridDatas.data[rowIndex];
			rows.push(row);
		}
		return rows;
	}
};
function cloneObject( o, deep)
{
    if ( o === null || o === undefined || typeof ( o ) !== 'object' )
    {
        return o;
    }

    if ( o.constructor === Array )
    {
        if ( deep === false )
        {
            return o;
        }

        cloned = [];

        for ( var i in o )
        {
            cloned.push( cloneObject( o[i], deep ) );
        }

        return cloned;
    }

    cloned = {};

    for ( var i in o )
    {
        cloned[i] = deep ? cloneObject( o[i], true ) : o[i];
    }

    return cloned;
}